package com.example.forum.exception;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class) // 要处理哪种异常
    public AppResult applicationException(ApplicationException e){
        // 打印异常信息,但是生产之前要删除
        e.printStackTrace();
        log.error(e.getMessage());
        if(e.getErrorResult()!=null){
            // 判断是否有效
            return e.getErrorResult();
        }
        // 非空校验
        if(e.getMessage() == null || e.getMessage().isEmpty()){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        // 返回具体的异常信息
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class) // 要处理哪种异常
    public AppResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        if(e.getMessage()==null||e.getMessage().isEmpty()){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }
}
